<?php

function get_user_token($t = '')
{
  if (empty($_SESSION['token_user'])) return false;

  list($id, $name, $rand_int) = explode('+', hex_bin($_SESSION['token_user']));

  switch ($t) {
    case 'id':
      $res = intval($id);
      break;

    case 'token':
      $res = $rand_int;
      break;

    case 'array':
      $res['id'] = $id;
      $res['name'] = $name;
      $res['token'] = $rand_int;
      break;

    default:
      $res = str_safe($name);
      break;
  }

  return $res;
}

function get_user_token_cookie()
{
  if (empty($_COOKIE['token_user'])) return false;

  list($id, $name, $rand_int) = explode('+', hex_bin($_COOKIE['token_user']));

  $res['id'] = $id;
  $res['name'] = $name;
  $res['token'] = $rand_int;

  return $res;
}

/**
 * limit_user_login
 * 限制同一用户的多终端登陆
 * 该函数依赖lib.base.php
 */
/*
function limit_user_login($u_id)
{
  $u_id = intval($u_id);

  $arr['session_id'] = session_id();
  if ($session_id = get_col("user_session", "session_id", "u_id = '" . $u_id . "'")) {
    if ($session_id != $arr['session_id']) {
      return $GLOBALS['db']->query("UPDATE user_session SET session_id = '" . $arr['session_id'] . "' WHERE u_id = '$u_id'");
    }
  } else {
    $arr['u_id'] = $u_id;
    return $GLOBALS['db']->autoExecute("user_session", $arr, "INSERT");
  }
}
*/

/**
 * 检测用户登录状态
 */
function check_user($url = '', $conf = true, $notice = true)
{
  // 判空
  if (empty($_COOKIE['token_user']) || empty($_SESSION['token_user'])) {
    if ($notice) {
      alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
    }
    href($url);
  }

  // 限制同一用户同时多端登录
  if ($conf) {
    if ($_COOKIE['token_user'] == $_SESSION['token_user']) {
      return true;
    }

    alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
  }

  $user_token = get_user_token('array');
  $user_token_cookie = get_user_token_cookie();

  if ($user_token['id'] != $user_token_cookie['id'] || $user_token['name'] != $user_token_cookie['name']) {
    alert_href($GLOBALS['lang']['uc']['check']['failed'], $url);
  }

  unset($user_token);
  unset($user_token_cookie);

  return true;
}

/**
 * 设置用户标示便于进一步安全判断
 * 用户id
 * 用户名
 */
function set_user_token($u_id, $u_name)
{
  $u_id = intval($u_id);
  $rand_int = str_code(6);

  $user_token = bin2hex($u_id . '+' . $u_name . '+' . $rand_int);
  set_cookie('token_user', $user_token, gmtime() + COOKIE_TIMEOUT);
  $_SESSION['token_user'] = $user_token;
}

/**
 * 用户退出
 */
function user_logout($url = '')
{
  $url = !empty($url) ? $url : M(str_safe($_GET['s']), 'index', 'login');
  set_cookie('token_user', '', gmtime() - COOKIE_EXPIRE);
  unset($_SESSION['token_user']);
  href($url);
  return;
}

function user_login_log($user_id, $login_type)
{
  $data['user_id'] = $user_id;
  $data['login_time'] = gmtime();
  $data['login_ip'] = get_ip();
  $data['login_type'] = $login_type;

  return $GLOBALS['db']->autoExecute('user_login_log', $data);
}

function get_userinfo()
{
  return $GLOBALS['db']->getRow("SELECT * FROM user WHERE id = " . get_user_token('id'));
}


function get_user_limit($user_id = 0)
{
  $user_id = $user_id ? $user_id : get_user_token('id');
  $site_config = file_get('json', 'site_config');
  $user_config = json_decode($GLOBALS['db']['db_user']->getOne("SELECT u_limit FROM user WHERE id = " . $user_id), true);
  $res = array();

  foreach ($site_config as $key => $val) {
    // 判断用户生效配置为2跳过,2为使用系统设置
    if (strpos($key, '_enable') !== false) {
      if ($user_config[$key] < 2 && isset($user_config[$key])) {
        $res[$key] = $user_config[$key];
        continue;
      }

      $res[$key] =  $val;
      continue;
    }

    // 判断用户配置不为0的限制数值替换系统配置值
    if ($user_config[$key] > 0) {
      $res[$key] = $user_config[$key];
      continue;
    }

    $res[$key] = $val;
  }

  // 加入不存在的用户配置
  foreach ($user_config as $key => $val) {
    if (isset($res[$key])) continue;

    $res[$key] = $user_config[$key];
  }

  return $res;
}

function get_cart_info($cart)
{
  $exclude = array('rowid', 'options');
  $str = '';
  foreach ($cart as $val) {
    foreach ($val as $k => $v) {
      if (in_array($k, $exclude) !== false) {
        continue;
      }
      $str .= $v . ',';
    }
    $str = rtrim($str, ",") . '|';
  }
  $str = rtrim($str, "|");
  return array(
    'u_id' => get_user_token('id'),
    'c_info' => $str,
    'c_qty' => $cart['total_items'],
    'c_cost' => $cart['cart_total'],
    'c_state' => 1,
    'c_date' => gmtime()
  );
}

function get_cart_item($t = 1)
{
  $str = $GLOBALS['db']->getOne("SELECT c_info FROM cart WHERE u_id = '" . get_user_token('id') . "'");
  $arr = explode("|", $str);
  foreach ($arr as $key => $value) {
    $arr_info = str_array($value);
    $res[$key]['id'] = $arr_info[0];
    $res[$key]['qty'] = $arr_info[1];
    $res[$key]['price'] = $arr_info[2];
    $res[$key]['name'] = $arr_info[3];
    if ($t) {
      $res[$key]['subtotal'] = $arr_info[4];
    }
  }
  return $res;
}

function get_order_info($cart)
{
  $exclude = array('rowid', 'options');
  $str = '';
  foreach ($cart as $val) {
    foreach ($val as $k => $v) {
      if (in_array($k, $exclude)) {
        continue;
      }
      $str .= $v . ',';
    }
    $str = rtrim($str, ",") . '|';
  }
  $str = rtrim($str, "|");
  return array(
    'u_id' => get_user_token('id'),
    'o_sn' => microtime_float(),
    'o_info' => $str,
    'o_qty' => $cart['total_items'],
    'o_cost' => $cart['cart_total'],
    'o_state' => 1,
    'o_date' => gmtime()
  );
}

function get_order_item($id, $t = 1)
{
  $id = intval($id);

  $str = $GLOBALS['db']->getOne("SELECT o_info FROM order WHERE id = '$id'");
  $arr = explode("|", $str);
  foreach ($arr as $key => $value) {
    $arr_info = str_array($value);
    $res[$key]['id'] = $arr_info[0];
    $res[$key]['qty'] = $arr_info[1];
    $res[$key]['price'] = $arr_info[2];
    $res[$key]['name'] = $arr_info[3];
    if ($t) {
      $res[$key]['subtotal'] = $arr_info[4];
    }
  }
  return $res;
}

function get_order_state($id)
{
  $id = intval($id);

  return $GLOBALS['db']->getOne("SELECT o_state FROM order WHERE id = '$id'");
}